
class PlainTextThing < Thing
  attr_accessor :content

  def recieve e
    if content = e.params[form_id(:text)]
      @content = content
    end
    super
  end


  def id
    'o'+object_id.to_s
  end

  def creator e
    Element.new(:textarea, @content.to_s,
      { :style => "width:99%;", :name => form_id(:text), :id => form_id(:text), :rows => count_rows+1 }
    )
  end

  def count_rows
    rows = 0
    (@content || '').split("\n").each { |line|
      rows += 1 + (line.length / 112).floor
    }
    rows
  end


  def render e
    @content
  end

  def format content
    content
  end

  def get_data
    { 'text' => @content }
  end

  def fill_data h
    @content = h['text']
  end
end

class FormatedTextThing < PlainTextThing

  def render e
    format @content
  end


end

class TextThing < FormatedTextThing

  def render e
    format @content
  end

  def format content
    require 'RedCloth'
    
    RedCloth.new(
      self.class.to_entities content
    ).to_html
  end

  def self.to_entities string
    require 'htmlentities'
    
    HTMLEntities.new.
      encode(string, :named, :decimal).
      gsub("&#13;&#10;", "\n").
      gsub("&quot;", "\"")
  end
end








class HtmlCode < PlainTextThing

  def creator e
    if e.data['page']
      e.page.head << <<JS
    <!-- CodeMirror -->
    <script src="/CodeMirror-0.65/js/codemirror.js" type="text/javascript"></script>
    <style>
      .CodeMirror-wrapping {
        border:1px inset gray;
      }
    </style>
JS
    end

    textarea = Element.new(:textarea, @content.to_s,
      { :style => "width:99%;",
        :name => (form_id :text),
        :id => (form_id :text),
        :rows => count_rows+1
      }
    )

    <<HTML
  #{textarea}

<script type="text/javascript">
try {
  var editor = CodeMirror.fromTextArea('#{id}', {
    height: '#{count_rows+2}em',
    parserfile: ["parsexml.js", "parsecss.js", "tokenizejavascript.js", "parsejavascript.js", "parsehtmlmixed.js"],
    stylesheet: ["/CodeMirror-0.65/css/xmlcolors.css", "/CodeMirror-0.65/css/jscolors.css", "/CodeMirror-0.65/css/csscolors.css"],
    path: "/CodeMirror-0.65/js/"
  });
} catch (e) {
 // something went wrong here
}
</script>
HTML

  end
end

class CssCode < PlainTextThing
  def creator e

    textarea = Element.new(:textarea, @content.to_s,
      { :name => id, :id => id, :rows => count_rows+1 }
    )

    <<HTML
  #{textarea}

<script type="text/javascript">
  var editor = CodeMirror.fromTextArea('#{id}', {
    height: '#{count_rows+2}em',
    parserfile: "parsecss.js",
    stylesheet: "/CodeMirror-0.65/css/csscolors.css",
    path: "/CodeMirror-0.65/js/"
  });
</script>
HTML

  end
end

